import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common.utils import ForumDriver


class ForumLogin:
    def __init__(self):
        self.driver=ForumDriver.driver
        self.url="http://127.0.0.1:58080/sign-in.html"
        self.driver.get(self.url)

    def _clear_forum(self):
        # 清除输入框
        self.driver.find_element(By.CSS_SELECTOR, "#username").clear()
        self.driver.find_element(By.CSS_SELECTOR, "#password").clear()

    def LoginSucc(self):
        self._clear_forum()
        self.driver.find_element(By.CSS_SELECTOR, "#username").send_keys("zhangsan")
        self.driver.find_element(By.CSS_SELECTOR, "#password").send_keys("123456")

        time.sleep(1)
        # 点击登录
        self.driver.find_element(By.CSS_SELECTOR, "#submit").click()
        time.sleep(1)
        # 验证登录成功后是否能看到字段“首页”
        wait = WebDriverWait(self.driver,10)
        wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="article_list_board_title"]')))
        # 截图
        ForumDriver.getScreenShot()

    def LoginFail(self):
        # 测试各种注册失败的情况
        test_cases = [
            # (描述, 用户名, 密码)
            ("用户名和密码都为空", "", ""),
            ("用户名为空", "", "11"),
            ("用户名不存在", "zzz", "11"),
            ("正确的用户名，密码为空", "zhangsan", ""),
            ("正确的用户名，密码错误", "zhangsan", "11")
        ]

        for desc, username, password in test_cases:
            self._clear_forum()
            # 对输入框
            if username:
                self.driver.find_element(By.CSS_SELECTOR, "#username").send_keys(username)
            if password:
                self.driver.find_element(By.CSS_SELECTOR, "#password").send_keys(password)

            time.sleep(3)
            # 点击登录
            self.driver.find_element(By.CSS_SELECTOR, "#submit").click()

            # 验证：如果登录失败，还是在登录界面
            curUrl = self.driver.current_url
            assert curUrl == "http://127.0.0.1:58080/sign-in.html"
            # 截图
            ForumDriver.getScreenShot()

# ForumLogin().LoginSucc()
# ForumLogin().LoginFail()
# ForumDriver.driver.quit()









